package com.boot.security.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.security.server.agency.Utils.InterfaceUtils;
import com.boot.security.server.agency.content.AgencyConstant;
import com.boot.security.server.agency.mapper.AgencyRecordMapper;
import com.boot.security.server.agency.model.domain.AgencyRecord;
import com.boot.security.server.agency.service.AgencyRecordService;
import com.boot.security.server.common.Result;
import com.boot.security.server.common.ResultBuilder;
import com.boot.security.server.contant.Constant;
import com.boot.security.server.dao.MOverseeQuestionDao;
import com.boot.security.server.dict.mapper.DataDictDetailsMapper;
import com.boot.security.server.dict.service.IDictService;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.enums.Check;
import com.boot.security.server.mapper.*;
import com.boot.security.server.model.OverseeQuestion;
import com.boot.security.server.model.domain.*;
import com.boot.security.server.model.param.OverseeQuestionParam;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.MOverseeQuestionService;
import com.boot.security.server.service.SysLogService;
import com.boot.security.server.user.mapper.SysUserMapper;
import com.boot.security.server.user.model.SysUser;
import com.boot.security.server.user.model.SysUsers;
import com.boot.security.server.user.service.UserService;
import com.boot.security.server.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class MOverseeQuestionServiceImpl implements MOverseeQuestionService {
    @Autowired
    private SysLogService logService;

    @Autowired
    private MOverseeQuestionDao mOverseeQuestionDao;
    @Autowired
    private MOverseeQuestionMapper overseeQuestionMapper;
    @Autowired
    private MAnnexMapper mAnnexMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private AgencyRecordService agencyRecordService;
    @Autowired
    private AgencyRecordMapper agencyRecordMapper;
    @Autowired
    private MQuestionRecordMapper mQuestionRecordMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MQuestionRecordMapper recordMapper;
    @Autowired
    private IDictService dictService;
    @Autowired
    private DataDictDetailsMapper detailsMapper;

    @Transactional
    @Override
    public Result agreeExamine (OverseeQuestionParam param) {
        MOverseeQuestion question = overseeQuestionMapper.selectByPrimaryKey(param.getQuestionId());
        if (! Constant.CHECKING.equals(question.getCheckStatus())) {
            return ResultBuilder.paramError("该问题已经审核过了，请勿重复操作");
        }

        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));
        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        MOverseeQuestion mOverseeQuestion = new MOverseeQuestion();
        mOverseeQuestion.setId(param.getQuestionId());
        mOverseeQuestion.setCheckStatus(Constant.CHECK_SUCCESS);
        mOverseeQuestion.setUpdateTime(new Date());
        mOverseeQuestion.setStatus(Constant.CHECK_SUCCESS);
        mOverseeQuestion.setAuditOpinion(param.getAuditOpinion());
        int i = overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);

        AgencyRecord agencyRecord = new AgencyRecord();
        agencyRecord.setRelationId(mOverseeQuestion.getId());
        agencyRecord.setType(Constant.PROCESS);
        agencyRecordService.delete(agencyRecord);

        param.setCheckStatus(mOverseeQuestion.getCheckStatus());

        return getResult(param, mOverseeQuestion, i);
    }

    @Transactional
    @Override
    public Result notAgreeExamine (OverseeQuestionParam param) {
        MOverseeQuestion question = overseeQuestionMapper.selectByPrimaryKey(param.getQuestionId());
        if (! Constant.CHECKING.equals(question.getCheckStatus())) {
            return ResultBuilder.paramError("该问题已经审核过了，请勿重复操作");
        }
        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));
        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        MOverseeQuestion mOverseeQuestion = overseeQuestionMapper.selectByPrimaryKey(param.getQuestionId());
        mOverseeQuestion.setId(param.getQuestionId());
        mOverseeQuestion.setCheckStatus(Constant.BACK);
        mOverseeQuestion.setUpdateTime(new Date());
        mOverseeQuestion.setStatus(Constant.BACK);
        mOverseeQuestion.setReviewer(mOverseeQuestion.getOversee());
        mOverseeQuestion.setAuditOpinion(param.getAuditOpinion());
        int i = overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);

        AgencyRecord agencyRecord = new AgencyRecord();
        agencyRecord.setRelationId(param.getQuestionId());
        agencyRecord.setType(Constant.PROCESS);
        AgencyRecord agency = agencyRecordService.findByRelation(agencyRecord);
        agency.setToUserId(mOverseeQuestion.getOverseeId());
        agency.setContent(AgencyConstant.BACK);
        agencyRecordService.update(agency);
        param.setCheckStatus(mOverseeQuestion.getCheckStatus());
        return getResult(param, mOverseeQuestion, i);
    }

    /**
     *
     **/
    private Result getResult (OverseeQuestionParam param, MOverseeQuestion mOverseeQuestion, int i) {
        if (i > 0) {
            // 修改成功写入问题记录表
            MQuestionRecord record = new MQuestionRecord();
            record.setOverseeForm(mOverseeQuestion.getOverseeForm());
            record.setBranch(mOverseeQuestion.getBranch());
            record.setCheckStatus(param.getCheckStatus());
            record.setOverseeQuestion(mOverseeQuestion.getQuestion());
            record.setQuestionStatus(mOverseeQuestion.getQuestionStatus());
            record.setOverseeQuestionId(mOverseeQuestion.getId());
            // 审核记录
            record.setType(1);
            if (StringUtils.isNotBlank(param.getAuditOpinion())) {
                record.setDetail(param.getAuditOpinion());
            }
            record.setCreateTime(new Date());
            LoginUser loginUser = UserUtil.getLoginUser();
            if (loginUser != null) {
                record.setUpdateUser(loginUser.getUsername());
            }
            if (StringUtils.isNotBlank(param.getFeedBackDate())) {
                record.setFeedBackDate(DateUtils.str2Date(param.getFeedBackDate()));
            }
            int i1 = mQuestionRecordMapper.insertSelective(record);
            if (i1 < 0) {
                return ResultBuilder.systemError("保存记录失败，请联系管理员！");
            }
            return ResultBuilder.success();
        }
        return ResultBuilder.systemError("保存问题记录失败！");
    }

    @Override
    public String getStatus (Long questionId) {
        // 查询问题状态
        MOverseeQuestion model = overseeQuestionMapper.selectByPrimaryKey(questionId);
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
            if (StringUtils.equals(model.getOversee(), user.getUsername())) {
                return "2";
            } else if (StringUtils.equals(model.getReviewer(), user.getUsername())) {
                if (model.getOverseeId() == UserUtil.getLoginUser().getId().intValue() && (model.getCheckStatus().equals(Constant.BACK))) {
                    return "2";
                }
                return "3";
            } else if (StringUtils.equals(user.getUsername(), "xtadmin")) {
                return "0";
            }
        }
        return "0";
    }

    @Override
    public String getYiBan (Integer id) {
        // 查询问题状态
        MOverseeQuestion mOverseeQuestion = overseeQuestionMapper.selectByPrimaryKey(id);

        LoginUser loginUser = UserUtil.getLoginUser();
        Long id1 = loginUser.getId();
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserid(id1.intValue());
        List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
        List<String> names = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            roleUsers.forEach(roleUser -> {
                SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                names.add(role.getName());
            });
        }
        if (names.contains(Constant.DBADMIN)) {
            return "2";
        } else {
            if (mOverseeQuestion.getOverseeId() == loginUser.getId().intValue()) {
                return "2";
            }
            return "3";
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveQuestion (OverseeQuestionParam param) {
        MOverseeQuestion mOverseeQuestion = BeanHelper.copyProperties(param, MOverseeQuestion.class);
        mOverseeQuestion.setCreateTime(new Date());
        mOverseeQuestion.setCheckStatus(Constant.CHECKING);
        mOverseeQuestion.setLiaison(param.getLiaison());
        if (UserUtil.getLoginUser() != null) {
            mOverseeQuestion.setOversee(UserUtil.getLoginUser().getUsername());
            mOverseeQuestion.setOverseeId(UserUtil.getLoginUser().getId().intValue());
        }
        mOverseeQuestion.setQuestionStatus(Constant.RECTIFICATION_ING);
        mOverseeQuestion.setBranchId(param.getBranchId());
        mOverseeQuestion.setBranch(param.getBranch());

        mOverseeQuestion.setStatus(Check.已提交待审核.toString());
        int i = overseeQuestionMapper.insertSelective(mOverseeQuestion);
        Integer id = mOverseeQuestion.getId();
        param.setQuestionId(id);
        param.setCheckStatus(mOverseeQuestion.getCheckStatus());
        param.setOverseeId(mOverseeQuestion.getOverseeId());
        getResult(param, mOverseeQuestion, i);
        return getResult(param, id);
    }

    @Override
    public Result updateQuestion (OverseeQuestionParam param) {
        MOverseeQuestion question = overseeQuestionMapper.selectByPrimaryKey(param.getQuestionId());

        // 审核通过问题生效不允许修改
        if (Constant.CHECK_SUCCESS.equals(question.getCheckStatus())) {
            return ResultBuilder.paramError("问题已经生效，不能修改!");
        }
        MOverseeQuestion mOverseeQuestion = BeanHelper.copyProperties(param, MOverseeQuestion.class);
        mOverseeQuestion.setUpdateTime(new Date());
        mOverseeQuestion.setBranch(param.getBranch());
        mOverseeQuestion.setBranchId(param.getBranchId());
        mOverseeQuestion.setCheckStatus(Constant.CHECKING);
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser != null) {
            mOverseeQuestion.setOversee(loginUser.getUsername());
            mOverseeQuestion.setOverseeId(loginUser.getId().intValue());
        }
        mOverseeQuestion.setId(param.getQuestionId());
        int i = overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);
        param.setOverseeId(param.getOverseeId());
        param.setQuestionId(mOverseeQuestion.getId());
        saveFile(param);

        AgencyRecord agencyRecord = new AgencyRecord();
        agencyRecord.setRelationId(param.getQuestionId());
        agencyRecord.setType(Constant.PROCESS);
        AgencyRecord record = agencyRecordService.findByRelation(agencyRecord);
        record.setCreateTime(new Date());
        record.setContent(AgencyConstant.CHECK);
        SysUser user = new SysUser();
        user.setUsername(param.getReviewer());
        List<SysUser> select = userMapper.select(user);
        SysUser sysUser = select.get(0);
        record.setToUserId(sysUser.getId());
        agencyRecordService.update(record);
        param.setCheckStatus(mOverseeQuestion.getCheckStatus());
        return getResult(param, mOverseeQuestion, i);
    }

    @Override
    public Result saveDrafts (OverseeQuestionParam param) {
        MOverseeQuestion mOverseeQuestion = BeanHelper.copyProperties(param, MOverseeQuestion.class);
        mOverseeQuestion.setCreateTime(new Date());
        mOverseeQuestion.setCheckStatus(Check.草稿中.toString());
        mOverseeQuestion.setBranch(param.getBranch());
        mOverseeQuestion.setBranchId(param.getBranchId());
        LoginUser loginUser = UserUtil.getLoginUser();
        mOverseeQuestion.setOversee(loginUser.getUsername());
        mOverseeQuestion.setOverseeId(loginUser.getId().intValue());
        mOverseeQuestion.setQuestionStatus(Constant.RECTIFICATION_ING);
        mOverseeQuestion.setStatus(Check.草稿中.toString());
        mOverseeQuestion.setStartPatrolTime(DateUtils.date2Str(new Date(), new SimpleDateFormat("yyyy")));
        int i = overseeQuestionMapper.insertSelective(mOverseeQuestion);
        param.setOverseeId(mOverseeQuestion.getOverseeId());
        param.setQuestionId(mOverseeQuestion.getId());
        saveFile(param);
        if (i > 0) {
            return ResultBuilder.success();
        }

        return ResultBuilder.systemError("保存失败！");
    }

    @Override
    public Result updateDrafts (OverseeQuestionParam param) {
        MOverseeQuestion mOverseeQuestion = BeanHelper.copyProperties(param, MOverseeQuestion.class);
        mOverseeQuestion.setCreateTime(new Date());
        mOverseeQuestion.setCheckStatus(Constant.CHECKING);
        mOverseeQuestion.setBranch(param.getBranch());
        LoginUser loginUser = UserUtil.getLoginUser();
        mOverseeQuestion.setOversee(loginUser.getUsername());
        mOverseeQuestion.setOverseeId(loginUser.getId().intValue());
        mOverseeQuestion.setQuestionStatus(Constant.RECTIFICATION_ING);
        mOverseeQuestion.setStatus(Check.草稿中.toString());
        int i = overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);
        param.setQuestionId(mOverseeQuestion.getId());
        param.setQuestionId(mOverseeQuestion.getId());
        saveFile(param);
        if (i > 0) {
            return ResultBuilder.success();
        }
        return ResultBuilder.systemError("修改失败！");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result draftsSave (OverseeQuestionParam param) {
        MOverseeQuestion mOverseeQuestion = BeanHelper.copyProperties(param, MOverseeQuestion.class);
        mOverseeQuestion.setCreateTime(new Date());
        mOverseeQuestion.setCheckStatus(Constant.CHECKING);
        LoginUser loginUser = UserUtil.getLoginUser();
        mOverseeQuestion.setOversee(loginUser.getUsername());
        mOverseeQuestion.setOverseeId(loginUser.getId().intValue());
        mOverseeQuestion.setQuestionStatus(Constant.RECTIFICATION_ING);
        mOverseeQuestion.setBranch(param.getBranch());
        mOverseeQuestion.setBranchId(param.getBranchId());
        mOverseeQuestion.setStartPatrolTime(DateUtils.date2Str(new Date(), new SimpleDateFormat("yyyy")));
        mOverseeQuestion.setStatus(Check.已提交待审核.toString());
        overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);
        Integer id = mOverseeQuestion.getId();
        return getResult(param, id);
    }

    /**
     *
     **/
    private Result getResult (OverseeQuestionParam param, Integer id) {
        // 插入附件
        saveFile(param);
        AgencyRecord agency = new AgencyRecord();
        agency.setRelationId(id);
        agency.setType(Constant.PROCESS);
        AgencyRecord agencyRecord = agencyRecordService.findByRelation(agency);
        int count;
        if (agencyRecord != null) {
            agencyRecord.setContent(AgencyConstant.CHECK);
            count = agencyRecordService.update(agencyRecord);
        } else {
            String url = String.format(AgencyConstant.QUESTION_URL, id);
            SysUser user = new SysUser();
            user.setUsername(param.getReviewer());
            List<SysUser> select = userMapper.select(user);
            SysUser sysUser = select.get(0);
            agency.setRelationUrl(url);
            agency.setContent(AgencyConstant.CHECK);
            agency.setToUserId(sysUser.getId());
            count = agencyRecordService.save(agency);
        }
        if (count > 0) {
            return ResultBuilder.success();
        }
        return ResultBuilder.systemError("代办提醒记录保存失败！");
    }

    @Transactional
    @Override
    public List<OverseeQuestion> findByStatus () {
        return mOverseeQuestionDao.findByStatus();
    }

    @Override
    public Result feedBack (OverseeQuestionParam param) {
        MOverseeQuestion mOverseeQuestion = overseeQuestionMapper.selectByPrimaryKey(param.getId());
        if (StringUtils.isBlank(mOverseeQuestion.getRemark())) {
            mOverseeQuestion.setEndPatrolTime(DateUtils.str2Date(param.getFeedBackDate()));
            mOverseeQuestion.setQuestionStatus(param.getQuestionStatus());
            mOverseeQuestion.setRemark(param.getRemark());
            overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);
            return ResultBuilder.success();
        } else {
            mOverseeQuestion.setQuestionStatus(param.getQuestionStatus());
            overseeQuestionMapper.updateByPrimaryKeySelective(mOverseeQuestion);
            param.setQuestionId(mOverseeQuestion.getId());
            param.setOverseeId(param.getOverseeId());
            saveFile(param);
            MQuestionRecord record = new MQuestionRecord();
            record.setOverseeForm(mOverseeQuestion.getOverseeForm());
            record.setBranch(mOverseeQuestion.getBranch());
            record.setCheckStatus(param.getCheckStatus());
            record.setOverseeQuestion(mOverseeQuestion.getQuestion());
            record.setQuestionStatus(mOverseeQuestion.getQuestionStatus());
            record.setOverseeQuestionId(mOverseeQuestion.getId());
            record.setType(2);
            if (StringUtils.isNotBlank(param.getRemark())) {
                record.setDetail(param.getRemark());
            }


            record.setCreateTime(new Date());
            LoginUser loginUser = UserUtil.getLoginUser();
            if (loginUser != null) {
                record.setUpdateUser(loginUser.getUsername());
            }
            if (StringUtils.isNotBlank(param.getFeedBackDate())) {
                record.setFeedBackDate(DateUtils.str2Date(param.getFeedBackDate()));
            }
            int i = mQuestionRecordMapper.insertSelective(record);
            if (i < 0) {
                return ResultBuilder.systemError("插入记录失败，请联系管理员！");
            }
            return ResultBuilder.success();
        }
    }

    /**
     * 插入附件
     * @param param
     */
    private void saveFile (OverseeQuestionParam param) {
        if (param.getBranchId() != null) {
            String value = detailsMapper.findDataValueByDataKeyAndDictId(param.getBranchId().toString(), 3);
            param.setBranch(value);
        }

        if (StringUtils.isNotBlank(param.getFile())) {

            // 多文件上传截取‘，’
            String[] path = param.getFile().split(",");
            for (String s : path) {
                MAnnex mAnnex = new MAnnex();
                mAnnex.setQuestion(param.getQuestion());
                mAnnex.setBranch(param.getBranch());
                mAnnex.setCreateTime(new Date());
                mAnnex.setQuestionId(param.getQuestionId());
                mAnnex.setType(1);
                mAnnex.setOverseeYear(DateUtils.date2Str(new Date(), new SimpleDateFormat("yyyy")));
                mAnnex.setDelated(0);
                mAnnex.setOverseeId(param.getOverseeId());
                String filePath = FileUtil.moveFiles(param.getBranch(), param.getQuestionType(), s);
                if (! "".equals(filePath)) {
                    mAnnex.setPath(filePath);
                } else {
                    throw new RuntimeException("文件有误，请检查！");
                }
                mAnnexMapper.insertSelective(mAnnex);
            }
        }
    }

    /**
     * 督办删除
     **/
    @Override
    public void deletePathOne (Integer id) {
        MAnnex mAnnex = new MAnnex();
        mAnnex.setId(id);
        mAnnex.setDelated(1);
        mAnnexMapper.updateByPrimaryKeySelective(mAnnex);

        AgencyRecord agency = new AgencyRecord();
        agency.setRelationId(id);
        String url = String.format(AgencyConstant.DEL_URL, id);
        agency.setRelationUrl(url);
        agency.setContent(AgencyConstant.DEL);
        MAnnex annex = mAnnexMapper.selectByPrimaryKey(id);
        MOverseeQuestion question = overseeQuestionMapper.selectByPrimaryKey(annex.getQuestionId());
        SysUser user = new SysUser();
        user.setUsername(question.getReviewer());
        List<SysUser> select = userMapper.select(user);
        SysUser sysUser = select.get(0);
        agency.setToUserId(sysUser.getId());
        agency.setType(Constant.FILE);
        agencyRecordService.save(agency);
    }

    /**
     *
     **/
    @Override
    public void deletePathDrafs (Integer id) {
        MAnnex mAnnex = new MAnnex();
        mAnnex.setId(id);
        mAnnex.setDelated(2);
        mAnnexMapper.updateByPrimaryKeySelective(mAnnex);
    }

    @Override
    public PageTableResponse yibanList (PageTableRequest request) {
        if (request.getParams().get(Constant.BRANCH_ID) != null && request.getParams().get(Constant.BRANCH_ID) != "") {
            String branch = request.getParams().get(Constant.BRANCH_ID).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH_ID, type);
        } else {
            request.getParams().remove(Constant.BRANCH_ID);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        if (request.getParams().get(Constant.QUESTION_TYPE) != null && request.getParams().get(Constant.QUESTION_TYPE) != "") {
            String questionType = request.getParams().get(Constant.QUESTION_TYPE).toString();
            List<String> type = JSONObject.parseArray(questionType, String.class);
            request.getParams().put(Constant.QUESTION_TYPE, type);
        } else {
            request.getParams().remove(Constant.QUESTION_TYPE);
        }

        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(loginUser.getId().intValue());
            List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(roleUser -> {
                    SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                    names.add(role.getName());
                });
            }
            if (names.contains(Constant.XTADMIN)) {
                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            } else {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                List<String> type = Arrays.asList(user.getBranch().split(","));
                if (CollectionUtils.isNotEmpty(type) && org.springframework.util.StringUtils.isEmpty(request.getParams().get(Constant.BRANCH_ID))) {
                    request.getParams().put(Constant.BRANCH_ID, type);
                }
                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            }
        }
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count (PageTableRequest request) {
                return mOverseeQuestionDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<OverseeQuestion> list (PageTableRequest request) {
                List<OverseeQuestion> list = mOverseeQuestionDao.list(request.getParams(), request.getOffset(), request.getLimit());
                for (OverseeQuestion overseeQuestion : list) {
                    String name = userService.getUserName(overseeQuestion.getOversee());
                    overseeQuestion.setOversee(name);
                    String name2 = userService.getUserName(overseeQuestion.getReviewer());
                    overseeQuestion.setReviewer(name2);
                }
                return list;
            }
        }).handle(request);
    }

    @Override
    public PageTableResponse draftsList (PageTableRequest request) {
        if (request.getParams().get(Constant.QUESTION_TYPE) != null && request.getParams().get(Constant.QUESTION_TYPE) != "") {
            String questionType = request.getParams().get(Constant.QUESTION_TYPE).toString();
            List<String> type = JSONObject.parseArray(questionType, String.class);
            request.getParams().put(Constant.QUESTION_TYPE, type);
        } else {
            request.getParams().remove(Constant.QUESTION_TYPE);
        }
        if (request.getParams().get(Constant.BRANCH_ID) != null && request.getParams().get(Constant.BRANCH_ID) != "") {
            String branch = request.getParams().get(Constant.BRANCH_ID).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH_ID, type);
        } else {
            request.getParams().remove(Constant.BRANCH_ID);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(loginUser.getId().intValue());
            List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(roleUser -> {
                    SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                    names.add(role.getName());
                });
            }
            if (names.contains(Constant.XTADMIN)) {
                request.getParams().put("status", Constant.DRAFTING);
            } else {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                List<String> type = Arrays.asList(user.getBranch().split(","));
                if (CollectionUtils.isNotEmpty(type) && org.springframework.util.StringUtils.isEmpty(request.getParams().get(Constant.BRANCH_ID))) {
                    request.getParams().put(Constant.BRANCH_ID, type);
                }
                request.getParams().put("status", Constant.DRAFTING);
                request.getParams().put("overseeId", loginUser.getId());
            }
        }
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count (PageTableRequest request) {
                return mOverseeQuestionDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<OverseeQuestion> list (PageTableRequest request) {
                List<OverseeQuestion> list = mOverseeQuestionDao.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }

    @Override
    public PageTableResponse list (PageTableRequest request) {
        if (request.getParams().get(Constant.BRANCH_ID) != null && request.getParams().get(Constant.BRANCH_ID) != "") {
            String branch = request.getParams().get(Constant.BRANCH_ID).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH_ID, type);
        } else {
            request.getParams().remove(Constant.BRANCH_ID);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        if (request.getParams().get(Constant.QUESTION_TYPE) != null && request.getParams().get(Constant.QUESTION_TYPE) != "") {
            String questionType = request.getParams().get(Constant.QUESTION_TYPE).toString();
            List<String> type = JSONObject.parseArray(questionType, String.class);
            request.getParams().put(Constant.QUESTION_TYPE, type);
        } else {
            request.getParams().remove(Constant.QUESTION_TYPE);
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        // 判断身份
        if (loginUser.getId() != null) {
            if (request.getParams().get(Constant.REVIEWER) != null && request.getParams().get(Constant.REVIEWER) != "") {
                request.getParams().remove(Constant.REVIEWER);
                request.getParams().put("checking", loginUser.getUsername());
            } else {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                if (StringUtils.equals(user.getUsername(), "xtadmin")) {
                    request.getParams().put("checkStatus", Constant.CHECKING);
                } else {
                    request.getParams().put("reviewer", loginUser.getUsername());
                }
            }
        }
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count (PageTableRequest request) {
                return mOverseeQuestionDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<OverseeQuestion> list (PageTableRequest request) {
                List<OverseeQuestion> list = mOverseeQuestionDao.list(request.getParams(), request.getOffset(), request.getLimit());
                for (OverseeQuestion overseeQuestion : list) {
                   String name = userService.getUserName(overseeQuestion.getOversee());
                   overseeQuestion.setOversee(name);
                    String name2 = userService.getUserName(overseeQuestion.getReviewer());
                    overseeQuestion.setReviewer(name2);
                }
                return list;
            }
        }).handle(request);
    }

    @Override
    public PageTableResponse allList (PageTableRequest request) {
        if (request.getParams().get(Constant.QUESTION_TYPE) != null && request.getParams().get(Constant.QUESTION_TYPE) != "") {
            String questionType = request.getParams().get(Constant.QUESTION_TYPE).toString();
            List<String> type = JSONObject.parseArray(questionType, String.class);
            request.getParams().put(Constant.QUESTION_TYPE, type);
        } else {
            request.getParams().remove(Constant.QUESTION_TYPE);
        }
        if (request.getParams().get(Constant.BRANCH_ID) != null && request.getParams().get(Constant.BRANCH_ID) != "") {
            String branch = request.getParams().get(Constant.BRANCH_ID).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH_ID, type);
        } else {
            request.getParams().remove(Constant.BRANCH_ID);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        if (request.getParams().get("oversee") != null && request.getParams().get("oversee") != "") {
            String oversee = request.getParams().get("oversee").toString();
            List<String> type = JSONObject.parseArray(oversee, String.class);
            request.getParams().put("oversee", type);
        } else {
            request.getParams().remove("oversee");
        }
        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(loginUser.getId().intValue());
            List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(roleUser -> {
                    SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                    names.add(role.getName());
                });
            }
            if (names.contains(Constant.XTADMIN)) {
                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            } else {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                String username = user.getUsername();
                // 查询本人提交和审核的问题
                request.getParams().put("personal", username);
                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            }
        }
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count (PageTableRequest request) {
                return mOverseeQuestionDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<OverseeQuestion> list (PageTableRequest request) {
                List<OverseeQuestion> list = mOverseeQuestionDao.list(request.getParams(), request.getOffset(), request.getLimit());
                for (OverseeQuestion overseeQuestion : list) {
                    String name = userService.getUserName(overseeQuestion.getOversee());
                    overseeQuestion.setOversee(name);
                    String name2 = userService.getUserName(overseeQuestion.getReviewer());
                    overseeQuestion.setReviewer(name2);
                }
                return list;
            }
        }).handle(request);
    }

    @Override
    public PageTableResponse detailList (PageTableRequest request) {
        if (request.getParams().get(Constant.QUESTION_TYPE) != null && request.getParams().get(Constant.QUESTION_TYPE) != "") {
            String questionType = request.getParams().get(Constant.QUESTION_TYPE).toString();
            List<String> type = JSONObject.parseArray(questionType, String.class);
            request.getParams().put(Constant.QUESTION_TYPE, type);
        } else {
            request.getParams().remove(Constant.QUESTION_TYPE);
        }
        if (request.getParams().get(Constant.QUESTION_STATUS) != null && request.getParams().get(Constant.QUESTION_STATUS) != "") {
            String questionStatus = request.getParams().get(Constant.QUESTION_STATUS).toString();
            List<String> type = JSONObject.parseArray(questionStatus, String.class);
            request.getParams().put(Constant.QUESTION_STATUS, type);
        } else {
            request.getParams().remove(Constant.QUESTION_STATUS);
        }
        if (request.getParams().get("oversee") != null && request.getParams().get("oversee") != "") {
            String oversee = request.getParams().get("oversee").toString();
            List<String> type = JSONObject.parseArray(oversee, String.class);
            request.getParams().put("oversee", type);
        } else {
            request.getParams().remove("oversee");
        }
        if (request.getParams().get(Constant.BRANCH_ID) != null && request.getParams().get(Constant.BRANCH_ID) != "") {
            String branch = request.getParams().get(Constant.BRANCH_ID).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH_ID, type);
        } else {
            request.getParams().remove(Constant.BRANCH_ID);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(loginUser.getId().intValue());
            List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(roleUser -> {
                    SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                    names.add(role.getName());
                });
            }
            if (names.contains(Constant.XTADMIN)) {
                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            } else {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                String username = user.getUsername();
                // 查询本人提交和审核的问题
                request.getParams().put("personal", username);

                request.getParams().put("checkStatus", Constant.CHECK_SUCCESS);
            }
        }
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count (PageTableRequest request) {
                return mOverseeQuestionDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<OverseeQuestion> list (PageTableRequest request) {
                List<OverseeQuestion> list = mOverseeQuestionDao.list(request.getParams(), request.getOffset(), request.getLimit());
                if (CollectionUtils.isNotEmpty(list)) {
                    list.forEach(overseeQuestion -> {
                        overseeQuestion.setAuditOpinion(XssUtils.convertStr(overseeQuestion.getAuditOpinion()));
                            String name = userService.getUserName(overseeQuestion.getOversee());
                            overseeQuestion.setOversee(name);
                        String name2 = userService.getUserName(overseeQuestion.getReviewer());
                        overseeQuestion.setReviewer(name2);
                    });
                }
                return list;
            }
        }).handle(request);
    }

    @Override
    public Result deleteYearReport (Integer id) {
        MAnnex annex = mAnnexMapper.selectByPrimaryKey(id);
        if (annex.getDelated() == 0 && annex.getOverseeId() != UserUtil.getLoginUser().getId().intValue()) {
            return ResultBuilder.paramError("请选择督办发起删除申请的报告");
        }
        if (annex.getDelated() == 1 && annex.getOverseeId() == UserUtil.getLoginUser().getId().intValue()) {
            return ResultBuilder.paramError("申请已经发出，请勿重复发送");
        }else if (annex.getDelated() == 1 && annex.getOverseeId() != UserUtil.getLoginUser().getId().intValue()){
            annex.setId(id);
            annex.setDelated(2);
            mAnnexMapper.updateByPrimaryKeySelective(annex);
            return ResultBuilder.success();
        }else if (annex.getDelated() == 0 && annex.getOverseeId() == UserUtil.getLoginUser().getId().intValue()){
            annex.setId(id);
            annex.setDelated(1);
            mAnnexMapper.updateByPrimaryKeySelective(annex);
            AgencyRecord agency = new AgencyRecord();
            agency.setRelationId(id);
            String url = String.format(AgencyConstant.DEL_URL, id);
            agency.setRelationUrl(url);
            agency.setContent(AgencyConstant.DEL);

            LoginUser loginUser = UserUtil.getLoginUser();
            List<Map<String, Object>> stringList = new ArrayList<>();
            if (loginUser.getId() != null) {
                SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
                if (! StringUtils.equals(user.getUsername(), "xtadmin")) {
                    SysUser sysUser = userMapper.selectByPrimaryKey(user.getUserId());
                    agency.setToUserId(sysUser.getId());
                    agency.setType(Constant.FILE);
                    agencyRecordService.save(agency);
                }
            }
        }

        return ResultBuilder.success();
    }

    /**
     *
     **/
    @Override
    public void deletePathTwo (Integer id) {

        MAnnex annex = mAnnexMapper.selectByPrimaryKey(id);


        MAnnex mAnnex = new MAnnex();
        mAnnex.setId(id);
        mAnnex.setDelated(2);
        mAnnexMapper.updateByPrimaryKeySelective(mAnnex);

        AgencyRecord agencyRecord = new AgencyRecord();
        agencyRecord.setRelationId(id);
        agencyRecord.setType(Constant.FILE);
        agencyRecordService.delete(agencyRecord);
    }

    @Override
    public void exportDetailed (List<OverseeQuestion> select, HttpServletResponse response) {
        AtomicInteger recordNum = new AtomicInteger();
        AtomicReference<Boolean> recordFlag = new AtomicReference<>(false);
        select.forEach(question -> {
            MQuestionRecord record = new MQuestionRecord();
            record.setOverseeQuestionId(Math.toIntExact(question.getId()));
            record.setType(2);
            List<MQuestionRecord> records = recordMapper.select(record);
            if (recordNum.get() < records.size()) {
                recordNum.set(records.size());
                recordFlag.set(true);
            }
        });
        try {
            /** 第一步，创建一个Workbook，对应一个Excel文件  */
            XSSFWorkbook wb = new XSSFWorkbook();
            /** 第二步，在Workbook中添加一个sheet,对应Excel文件中的sheet  */
            XSSFSheet sheet = wb.createSheet("sheet");
            /** 第三步，设置样式以及字体样式*/
            XSSFCellStyle titleStyle = createCellTitleStyle(wb);
            XSSFCellStyle style = createCellStyle(wb);
            /** 第四步，创建标题 ,合并标题单元格 */
            // 行号
            AtomicInteger rowNum = new AtomicInteger();
            // 创建第一页的第一行，索引从0开始
            XSSFRow row0 = sheet.createRow(rowNum.getAndIncrement());
            int ss = 10 + recordNum.get() * 3;
            List<String> oneLine = new ArrayList<>(ss);
            oneLine.add("巡察单位");
            oneLine.add("巡察年度");
            oneLine.add("督办员");
            oneLine.add("问题类别");
            oneLine.add("问题项");
            oneLine.add("问题来源");
            oneLine.add("问题描述");
            oneLine.add("巡察回访");
            oneLine.add("");
            oneLine.add("");
            if (recordFlag.get()) {
                for (int i = 0; i < recordNum.get(); i++) {
                    oneLine.add(10 + 3 * i, "整改跟踪");
                    oneLine.add(11 + 3 * i, "");
                    oneLine.add(12 + 3 * i, "");
                }
            }
            for (int i = 0; i < ss; i++) {
                XSSFCell tempCell = row0.createCell(i);
                tempCell.setCellValue(oneLine.get(i));
                tempCell.setCellStyle(titleStyle);
            }
            // 合并 "巡察年度", "督办员", "问题类别", "问题项", "问题来源", "问题描述", "巡察回访","整改跟踪"
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 4, 4));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 5, 5));
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 6, 6));
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 7, 9));
            if (recordFlag.get()) {
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 9, ss - 1));
            }
            //第二行
            XSSFRow row1 = sheet.createRow(rowNum.getAndIncrement());
            List<String> twoLine = new ArrayList<>(ss);
            for (int i = 0; i < 7; i++) {
                twoLine.add(i, "");
            }
            twoLine.add(7, "整改进度");
            twoLine.add(8, "整改落实情况");
            twoLine.add(9, "回访时间");
            if (recordFlag.get()) {
                for (int i = 0; i < recordNum.get(); i++) {
                    twoLine.add(10 + 3 * i, "整改进度");
                    twoLine.add(11 + 3 * i, "跟踪进展");
                    twoLine.add(12 + 3 * i, "跟踪时间");
                    sheet.setColumnWidth(10 + 3 * i, 15 * 256);
                    sheet.setColumnWidth(11 + 3 * i, 60 * 256);
                    sheet.setColumnWidth(12 + 3 * i, 15 * 256);
                }
            }
            for (int i = 0; i < ss; i++) {
                XSSFCell tempCell = row1.createCell(i);
                tempCell.setCellValue(twoLine.get(i));
                tempCell.setCellStyle(titleStyle);
            }

            select.forEach(question -> {
                MQuestionRecord record = new MQuestionRecord();
                record.setOverseeQuestionId(Math.toIntExact(question.getId()));
                record.setType(2);
                List<MQuestionRecord> records = recordMapper.select(record);

                XSSFRow tempRow = sheet.createRow(rowNum.getAndIncrement());
                // 行高
                // tempRow.setHeight((short) (10 * 20));
                for (int i = 0; i < ss; i++) {
                    XSSFCell tempCell = tempRow.createCell(i);
                    String tempValue = "";
                    if (i == 0) {
                        tempValue = question.getBranch();
                    } else if (i == 1) {
                        tempValue = question.getStartPatrolTime();
                    } else if (i == 2) {
                        tempValue = question.getOversee();
                    } else if (i == 3) {
                        tempValue = question.getQuestionType();
                    } else if (i == 4) {
                        tempValue = question.getQuestion();
                    } else if (i == 5) {
                        tempValue = question.getSourceProblem();
                    } else if (i == 6) {
                        tempValue = question.getQuestionDetail();
                    } else if (i == 7) {
                        tempValue = question.getQuestionStatus();
                    } else if (i == 8) {
                        tempValue = XssUtils.convertStr(question.getRemark());
                    } else if (i == 9) {
                        tempValue = DateUtils.date2Str(question.getUpdateTime());
                    }
                    if (recordFlag.get()) {
                        for (int j = 0; j < records.size(); j++) {
                            if (i == 10 + 3 * j) {
                                tempValue = records.get(j).getQuestionStatus();
                            } else if (i == 11 + 3 * j) {
                                tempValue = XssUtils.convertStr(records.get(j).getDetail());
                            } else if (i == 12 + 3 * j) {
                                tempValue = DateUtils.date2Str(records.get(j).getCreateTime());
                            }
                        }
                    }
                    tempCell.setCellValue(tempValue);
                    tempCell.setCellStyle(style);
                }
            });

            sheet.setColumnWidth(0, 15 * 256);
            sheet.setColumnWidth(1, 15 * 256);
            sheet.setColumnWidth(2, 20 * 256);
            sheet.setColumnWidth(3, 30 * 256);
            sheet.setColumnWidth(4, 20 * 256);
            sheet.setColumnWidth(5, 50 * 256);
            sheet.setColumnWidth(6, 50 * 256);
            sheet.autoSizeColumn(7);
            sheet.setColumnWidth(8, 60 * 256);
            sheet.setColumnWidth(9, 15 * 256);

            //导出Excel对象
            String fileName = URLEncoder.encode("问题督办明细台账.xlsx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
            OutputStream stream = response.getOutputStream();
            if (null != wb && null != stream) {
                // 将数据写出去
                wb.write(stream);
                stream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
    }

    @Override
    public void agencyLogin (Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {

        /*String servletPath = request.getRequestURI();
        HttpSession session = request.getSession();
        String userId = null;// 用户登录名
        // 检查Cookie获得 SSO Token
        String token = InterfaceUtils.checkCookie(request);
        System.out.println("getToken=======>"+token);
        // 验证登录
        if (token != null) {
            userId = InterfaceUtils.SSOTokenLoginGetCode(token);
            System.out.println("loginid=========》"+userId);
            //log.info("登录工号，{}",userId);
        }
        // 根据工号查用户
        System.out.println("Userid=======>"+userId);
        SysUsers user = userService.getUserByOa(userId);
        System.out.println("selectUser======>"+(user==null));*/
        SysUsers user = null;
        AgencyRecord record = null;
        if (id != null && id != 0 ) {
             record = agencyRecordMapper.selectByPrimaryKey(id);
            user = userService.getById(record.getToUserId().longValue());
            user.setUl(record.getRelationUrl());
        }
        String ip = IpUtils.getIpAddress(request);
        logService.save(user.getId(),"oa代办跳转",true,ip + "==处理" + record.getType());
        if (user != null && user.getPassword() != null && user.getPassword().length() > 0) {
            response.getWriter().write(JSON.toJSONString(user));
        } else {
            throw new Exception("未找到相应用户信息!");
        }
    }

    @Override
    public Map<String, Object> file (Integer id,Integer userId) {
        List<SysUsers> users = null;
        if (userId != 0){
            users = userService.getByPid(userId);
        }
        List<MAnnex> annexes = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(users) && id == 0){
            for (SysUsers user : users) {
                MAnnex example = new MAnnex();
                example.setDelated(1);
                example.setOverseeId(user.getId().intValue());
                List<MAnnex> select = mAnnexMapper.select(example);
                annexes.addAll(select);
            }
        }
        if (id != 0){
            MAnnex example = new MAnnex();
            example.setDelated(1);
            example.setId(id);
            MAnnex annex = mAnnexMapper.selectOne(example);
            annexes.add(annex);
        }

        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(annexes)) {
            for (MAnnex annex : annexes) {
                annex.setType(3);
                File startFile = new File(annex.getPath());
                String fileName = startFile.getName();
                annex.setPath(fileName.substring(15));
            }
        }

        map.put("code", 0);
        map.put("msg", "");
        map.put("count", annexes.size());
        map.put("data", annexes);
        return map;
    }

    /**
     *
     **/
    @Override
    public Result saveReport (MAnnex mAnnex) {
        String path = FileUtil.moveFiles(mAnnex.getBranch(), "年度报告", mAnnex.getPath());
        mAnnex.setPath(path);

        int i = mAnnexMapper.insertSelective(mAnnex);

        return ResultBuilder.success();
    }

    @Override
    public void export (List<OverseeQuestion> mOverseeQuestions, HttpServletResponse response) {
        if (CollectionUtils.isNotEmpty(mOverseeQuestions)) {
            mOverseeQuestions.forEach(question -> {
                question.setQuestionDetail(XssUtils.convertStr(question.getQuestionDetail()));
                question.setQuestion(XssUtils.convertStr(question.getQuestion()));
                question.setLiaison(XssUtils.convertStr(question.getLiaison()));
            });
        }
        try {
            List<ExcelBean> excel = new ArrayList<>();
            Map<Integer, List<ExcelBean>> map = new LinkedHashMap<>();
            //设置标题栏
            excel.add(new ExcelBean("巡察单位", Constant.BRANCH, 0));
            excel.add(new ExcelBean("巡察年度", Constant.START_PATROL_TIME, 0));
            excel.add(new ExcelBean("督办员", Constant.LIAISON, 0));
            excel.add(new ExcelBean("问题类别", Constant.QUESTION_TYPE, 0));
            excel.add(new ExcelBean("问题项", Constant.QUESTION, 0));
            excel.add(new ExcelBean("整改进度", Constant.QUESTION_STATUS, 0));
            map.put(0, excel);
            String recipe = "问题督办汇总台账";
            //导出Excel对象
            XSSFWorkbook workbook = ExcelUtils.createExcelFile(OverseeQuestion.class, mOverseeQuestions, map, recipe);
            String filename = URLEncoder.encode("问题督办汇总台账", "UTF-8");
            ExportUtil.dataWriteResponse(response, workbook, filename);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private XSSFCellStyle createCellTitleStyle (XSSFWorkbook wb) {
        XSSFCellStyle setBorder = wb.createCellStyle();
        //设置填充方案
        setBorder.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //设置填充颜色
        setBorder.setFillForegroundColor(new XSSFColor(new Color(172, 186, 202)));
        // 下边框
        setBorder.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        // 左边框
        setBorder.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        // 上边框
        setBorder.setBorderTop(XSSFCellStyle.BORDER_THIN);
        // 右边框
        setBorder.setBorderRight(XSSFCellStyle.BORDER_THIN);
        // 居中
        setBorder.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 垂直
        setBorder.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 创建字体样式
        XSSFFont font = wb.createFont();
        // 设置字体类型
        font.setFontName("黑体");
        // 粗体显示
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体大小
        font.setFontHeightInPoints((short) 14);
        // 为标题样式设置字体样式
        setBorder.setFont(font);
        return setBorder;
    }

    private XSSFCellStyle createCellStyle (XSSFWorkbook wb) {
        XSSFCellStyle setBorder = wb.createCellStyle();
        // 设置自动换行
        setBorder.setWrapText(true);
        // 下边框
        setBorder.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        // 左边框
        setBorder.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        // 上边框
        setBorder.setBorderTop(XSSFCellStyle.BORDER_THIN);
        // 右边框
        setBorder.setBorderRight(XSSFCellStyle.BORDER_THIN);
        // 居中
        setBorder.setAlignment(XSSFCellStyle.ALIGN_LEFT);
        // 垂直
        setBorder.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 创建字体样式
        XSSFFont font = wb.createFont();
        // 设置字体类型
        font.setFontName("黑体");
        // 设置字体大小
        font.setFontHeightInPoints((short) 14);
        // 为标题样式设置字体样式
        setBorder.setFont(font);
        return setBorder;
    }
}
